﻿@using Flagrum.Web.Features.Settings.Data
@using Flagrum.Core.Utilities
@using Flagrum.Core.Utilities.Types
@inject IStringLocalizer<ProfilesPage> Localizer
@inject ProfileService Profile

<AutosizeModal @ref="Modal">
    <HeaderView>
        <span class="text-grey-300 flex-grow">@(IsNew ? Localizer["NewProfile"] : Localizer["EditProfile"])</span>
        <span class="material-icons cursor-pointer" @onclick="Close">cancel</span>
    </HeaderView>
    <BodyView>
        <EditForm Model="Model" OnSubmit="OnSubmit">
            <DataAnnotationsValidator/>
            <label class="block">@Localizer["ProfileName"]</label>
            <Textbox @bind-Value="Model.Name" Size="Textbox.Variant.Stretch" />
            <ValidationMessage For="() => Model.Name" />
            
            <label class="block mt-4">@Localizer["ProfileType"]</label>
            <EnumSelect TEnum="LuminousGame" @bind-Value="Model.Type" Style="min-width: 300px;"/>
            
            <Button Icon="save" Text="Save" CssClass="mt-6" Type="submit" />
        </EditForm>
    </BodyView>
</AutosizeModal>

@code
{
    [CascadingParameter]
    public MainLayout MainLayout { get; set; }
    
    [CascadingParameter]
    public ProfilesPage Parent { get; set; }
    
    private bool IsNew { get; set; }
    private FlagrumProfile Model { get; set; } = new();
    
    private AutosizeModal Modal { get; set; }

    public void Open(FlagrumProfile profile)
    {
        if (profile == null)
        {
            IsNew = true;
            Model = new FlagrumProfile
            {
                Id = Guid.NewGuid().ToString()
            };
        }
        else
        {
            IsNew = false;
            
            // Make a clone so changes won't persist if the user cancels out of the modal
            Model = profile.DeepClone();
        }
        
        Modal.Open();
    }

    private void Close() => Modal.Close();

    private void OnSubmit()
    {
        if (IsNew)
        {
            Profile.Add(Model);
        }
        else
        {
            Profile.Update(Model);
            MainLayout.UpdateMenuState();
        }

        Parent.CallStateHasChanged();
        Modal.Close();
    }
}
